package com.momo.consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

@RestController
public class ConsumerController {


    @Autowired
    DiscoveryClient discoveryClient;//注意这里不要导错包，我们用的是cloud 包下的


    /**
     * 发送是定的provider 服务（地址写死了 ）
     * @return
     */
    @RequestMapping("/helloConsumer")
    public String helloConsumer(){
        //这里使用HttpUrlConnection
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL("http://localhost:1114/hello");
            httpURLConnection = (HttpURLConnection)url.openConnection();
            if(httpURLConnection.getResponseCode() == 200 ){
                BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String s = br.readLine();
                System.out.println(s);
                br.close();
                return s;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }




    /**
     * 由于已经注册Eureka中所以这里可以直接访问EurekaServer注册表中的相关信息
     * @return
     */
    @RequestMapping("/helloConsumer2")
    public String helloConsumer2(){
        /*
          这里思考，为什么是一个集群？ 因为这个Client也有可能是集群的模式
         */
        List<ServiceInstance> instances = discoveryClient.getInstances("my-provider");//根据服务名称获取对应服务实例
        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();//获取host地址
        int port = serviceInstance.getPort();//获取端口号
        StringBuffer sb = new StringBuffer();
        sb.append("http://")
                .append(host)
                .append(":")
                .append(port)
                .append("/hello");
        //这里使用HttpUrlConnection
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(sb.toString());
            httpURLConnection = (HttpURLConnection)url.openConnection();
            if(httpURLConnection.getResponseCode() == 200 ){
                BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String s = br.readLine();
                System.out.println(s);
                br.close();
                return s;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }
}
